package com.yunkaweilai.android.activity.shop;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.lazylibrary.util.StringUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.MyDialogInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.shop.ShopInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.MyToast;
import com.yunkaweilai.android.view.dialog.MyDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.SinglePicker;

public class PtShopPandianActivity extends BaseActivity implements MyDialogInterface {
    @BindView(R.id.id_shop_img)
    ImageView idShopImg;
    @BindView(R.id.id_tv_shop_name)
    TextView idTvShopName;
    @BindView(R.id.id_tv_shop_type)
    TextView idTvShopType;
    @BindView(R.id.id_tv_shop_num)
    TextView idTvShopNum;
    @BindView(R.id.line_add)
    LinearLayout lineadd;
    @BindView(R.id.line_out)
    LinearLayout lineout;
    @BindView(R.id.line_change)
    LinearLayout linechange;
    //入库
    @BindView(R.id.id_tv_ruku_num)
    EditText idETRKnum;
    @BindView(R.id.id_tv_ruku_money)
    EditText idETRKmoney;
    @BindView(R.id.id_ruku_time)
    TextView idTVRKtime;
    @BindView(R.id.id_tv_ruku_remark)
    EditText idETRKremark;
    //出库
    @BindView(R.id.id_tv_chuku_num)
    EditText idETCKnum;
    @BindView(R.id.id_tv_chuku_money)
    EditText idETCKmoney;
    @BindView(R.id.id_chuku_time)
    TextView idTVCKtime;
    @BindView(R.id.id_tv_chuku_remark)
    EditText idETCKremark;
    @BindView(R.id.id_chuku_type)
    TextView idTVCKtype;
    //调整
    @BindView(R.id.id_tv_change_num)
    EditText idETCHANGEnum;
    @BindView(R.id.id_tv_change_remark)
    EditText idETCHANGEremark;
    //确定按钮
    @BindView(R.id.id_btn_right)
    Button idBTNright;

    public static String PANDIAN_SHOP_MODEL = "PANDIAN_SHOP_MODEL";
    public static String PANDIAN_SHOP_BUNDLE = "PANDIAN_SHOP_BUNDLE";
    public static String TYPE_ADD = "RUKU";//入库
    public static String TYPE_OUT = "CHUKU";//出库
    public static String TYPE_CHANGE = "CHANGE";//调整
    private String type = "";
    private ShopInfoModel shopInfoModel = new ShopInfoModel();
    private int mYear = 0;
    private int mMonth = 0;
    private int mDay = 0;
    private String GoodsOutType = "0";

    public static void actionStart(Context context, ShopInfoModel shopInfoModel, String Type) {
        Intent intent = new Intent(context, PtShopPandianActivity.class);
        intent.putExtra("TYPE", Type);
        Bundle bundle = new Bundle();
        bundle.putSerializable(PANDIAN_SHOP_MODEL, shopInfoModel);
        intent.putExtra(PANDIAN_SHOP_BUNDLE, bundle);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptshop_pandian);
        ButterKnife.bind(this);
        initDate();
        //获取参数
        shopInfoModel = (ShopInfoModel) getIntent().getBundleExtra(PANDIAN_SHOP_BUNDLE).getSerializable(PANDIAN_SHOP_MODEL);
        type = getIntent().getStringExtra("TYPE");
        ShopInfoModel.DataBean.InfoBean info = shopInfoModel.getData().getInfo();
        Utils.shopInfoImg(mAc, info.getGoods_image(), idShopImg);
        idTvShopName.setText(info.getGoods_name() + "");//名称
        idTvShopType.setText("类别：" + info.getGoods_category_name() + "    条码：" + info.getGoods_sku());
        idTvShopNum.setText("库存：" + info.getMay_use_stock() + "  已销售：" + info.getSuccess_num());
        if (type.equals(TYPE_ADD)) {
            lineadd.setVisibility(View.VISIBLE);
            initviewAdd();
        } else if (type.equals(TYPE_OUT)) {
            lineout.setVisibility(View.VISIBLE);
            initviewOut();
        } else if (type.equals(TYPE_CHANGE)) {
            linechange.setVisibility(View.VISIBLE);
            initviewChange();
        }

        idBTNright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = "";
                if (type.equals(TYPE_ADD)) {
                    s = "是否确定入库？";
                    if (StringUtils.isEmpty(idETRKnum.getText().toString())) {
                        showToast("入库数量不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(idETRKmoney.getText().toString())) {
                        showToast("进货单价不能为空");
                        return;
                    }
                } else if (type.equals(TYPE_OUT)) {
                    s = "是否确定出库？";
                    if (StringUtils.isEmpty(idETCKnum.getText().toString())) {
                        MyToast.showShortToast(mAc, "出库数量不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(idETCKmoney.getText().toString())) {
                        MyToast.showShortToast(mAc, "出库单价不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(idTVCKtype.getText().toString())) {
                        MyToast.showShortToast(mAc, "请选择出库类型");
                        return;
                    }
                } else {
                    s = "是否确定调整？";
                    if (StringUtils.isEmpty(idETCHANGEnum.getText().toString())) {
                        showToast("调整数量不能为空");
                        return;
                    }
                }
                MyDialog myDialog = new MyDialog(mAc, PtShopPandianActivity.this, "提示", s);
                myDialog.show();
            }
        });

    }

    @SuppressLint("SetTextI18n")
    private void initviewAdd() {
        new TitleBuilder(mAc).setTitleText("商品入库").setLeftImage(R.mipmap.ic_go_back).setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        idETRKnum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        idETCKnum.setText(s);
                        idETCKnum.setSelection(s.length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        idTVRKtime.setText(mYear + "-" + mMonth + "-" + mDay);
        idTVRKtime.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
        idETRKmoney.setText(shopInfoModel.getData().getInfo().getGoods_purchase_price());
        idTVRKtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final DatePicker picker = new DatePicker(mAc);
                picker.setCanLoop(false);
                picker.setWheelModeEnable(true);
                picker.setTopPadding(15);
                picker.setRangeStart(1930, 1, 01);
                picker.setRangeEnd(mYear + 100, 11, 11);
                picker.setSelectedItem(mYear, mMonth, mDay);
                picker.setWeightEnable(true);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        idTVRKtime.setText(year + "-" + month + "-" + day);
                        idTVRKtime.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    }
                });
                picker.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
                    }
                });
                picker.show();
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void initviewOut() {
        new TitleBuilder(mAc).setTitleText("商品出库").setLeftImage(R.mipmap.ic_go_back).setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        idETCKnum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        idETCKnum.setText(s);
                        idETCKnum.setSelection(s.length());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        idTVCKtime.setText(mYear + "-" + mMonth + "-" + mDay);
        idTVCKtime.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
        idETCKmoney.setText(shopInfoModel.getData().getInfo().getGoods_purchase_price());
        initCKtype();
        idTVCKtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final DatePicker picker = new DatePicker(mAc);
                picker.setCanLoop(false);
                picker.setWheelModeEnable(true);
                picker.setTopPadding(15);
                picker.setRangeStart(1930, 1, 01);
                picker.setRangeEnd(mYear + 100, 11, 11);
                picker.setSelectedItem(mYear, mMonth, mDay);
                picker.setWeightEnable(true);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        idTVCKtime.setText(year + "-" + month + "-" + day);
                        idTVCKtime.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    }
                });
                picker.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
                    }
                });
                picker.show();
            }
        });

    }

    private void initCKtype() {
        final String[] Items = {"采购退货", "销售退货", "商品报废", "库存盘点损失", "其他"};//下拉框选项
        final String[] Items2 = {"1", "2", "3", "4", "5"}; //下拉框选项对应的inithttp传值
        idTVCKtype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SinglePicker<String> picker = new SinglePicker<>(mAc, Items);
                picker.setCanLoop(false);//不禁用循环
                picker.setLineVisible(true);
                picker.setShadowVisible(true);
                picker.setTextSize(18);
                picker.setSelectedIndex(0);
                picker.setWheelModeEnable(true);
                //启用权重 setWeightWidth 才起作用
                picker.setWeightEnable(true);
                picker.setWeightWidth(1);
                picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
                picker.setUnSelectedTextColor(0xFF999999);
                picker.setOnItemPickListener(new OnItemPickListener<String>() {
                    @Override
                    public void onItemPicked(int index, String item) {
                        GoodsOutType = Items2[index];
                        idTVCKtype.setText(item);
                        idTVCKtype.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
                    }
                });
                picker.show();
            }
        });


    }

    private void initviewChange() {
        new TitleBuilder(mAc).setTitleText("调整库存").setLeftImage(R.mipmap.ic_go_back).setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void inithttp() {
        if (type.equals(TYPE_ADD)) {
            HttpRequest.postUrl(Api.PTSHOP_SAVE_PUT)
                    .addParams("sku_id", shopInfoModel.getData().getInfo().getSkuList().get(0).getSku_id())
                    .addParams("PutStock", idETRKnum.getText().toString())
                    .addParams("PurchasePrice", idETRKmoney.getText().toString())
                    .addParams("put_time", idTVRKtime.getText().toString())
                    .addParams("remark", idETRKremark.getText().toString())
                    .executeToken(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkcode = Utils.checkCode(mAc, json);
                            if (checkcode) {
                                showToast("入库成功");
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_INFO_REFRESH, true));
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_LIST_REFRESH, true));
                                finish();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            showToast(e.getMessage());
                        }
                    });

        }
        if (type.equals(TYPE_OUT)) {
            HttpRequest.postUrl(Api.PTSHOP_SAVE_OUT)
                    .addParams("sku_id", shopInfoModel.getData().getInfo().getSkuList().get(0).getSku_id())
                    .addParams("OutStock", idETCKnum.getText().toString())
                    .addParams("OutPrice", idETCKmoney.getText().toString())
                    .addParams("GoodsOutType", GoodsOutType)
                    .addParams("out_time", idTVCKtime.getText().toString())
                    .addParams("remark", idETCKremark.getText().toString())
                    .executeToken(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkcode = Utils.checkCode(mAc, json);
                            if (checkcode) {
                                showToast("出库成功");
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_INFO_REFRESH, true));
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_LIST_REFRESH, true));
                                finish();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            showToast(e.getMessage());
                        }
                    });
        }
        if (type.equals(TYPE_CHANGE)) {
            HttpRequest.postUrl(Api.PTSHOP_CONFIRM_CHANGE)
                    .addParams("sku_id", shopInfoModel.getData().getInfo().getSkuList().get(0).getSku_id())
                    .addParams("TinkerUpStock", idETCHANGEnum.getText().toString())
                    .addParams("remark", idETCHANGEremark.getText().toString())
                    .executeToken(new PostProcess.StringCallBack() {
                        @Override
                        public void onResponse(String json) {
                            boolean checkcode = Utils.checkCode(mAc, json);
                            if (checkcode) {
                                showToast("调整成功");
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_INFO_REFRESH, true));
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_LIST_REFRESH, true));
                                finish();
                            }
                        }

                        @Override
                        public void onError(Exception e) {
                            showToast(e.getMessage());
                        }
                    });
        }
    }

    private void initDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = c.get(Calendar.YEAR);// 获取当前年份
        mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
    }

    @Override
    public void RightClick() {
        inithttp();
    }

    @Override
    public void CancelClick() {

    }
}
